package com.king.tv.mvp.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.king.base.util.ToastUtils;
import com.king.tv.App;
import com.king.tv.R;
import com.king.tv.bean.NoticeInfo;
import com.king.tv.bean.ShareInfo;
import com.king.tv.dao.greendao.bean.Price;
import com.king.tv.dao.greendao.bean.User;
import com.king.tv.dao.greendao.bean.contactus;
import com.king.tv.dao.greendao.manager.ManagerFactory;
import com.king.tv.http.BaseCallModel;
import com.king.tv.http.HttpLoader;
import com.king.tv.mvp.activity.ContactActivity;
import com.king.tv.mvp.activity.NoticeActivity;

import com.king.tv.util.FileUtil;
import com.king.tv.util.SPUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import gdut.bsx.share2.Share2;
import gdut.bsx.share2.ShareContentType;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/3/9
 */

public class MineFragment extends SimpleFragment {
    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.ivAvatar)
    ImageView ivAvatar;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.tvFollow)
    TextView tvFollow;
    @BindView(R.id.tvFans)
    TextView tvFans;
    @BindView(R.id.tvNiuBi)
    TextView tvNiuBi;
    @BindView(R.id.tvSeed)
    TextView tvSeed;
    @BindView(R.id.tvRecharge)
    TextView tvRecharge;
    @BindView(R.id.tvStarLight)
    TextView tvStarLight;
    @BindView(R.id.tvContribution)
    TextView tvContribution;
    @BindView(R.id.tvWatch)
    TextView tvWatch;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    @BindView(R.id.tvTask)
    TextView tvTask;
    @BindView(R.id.tvGame)
    TextView tvGame;
    @BindView(R.id.tvSetting)
    TextView tvSetting;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.fab)
    View fab;
    @BindView(R.id.tvMineName)
    TextView tvMineName;
    @BindView(R.id.tvVipTime)
    TextView tvVipTime;
    @BindView(R.id.tvMineCode)
    TextView tvcode;
    Unbinder unbinder;

    private User user;

    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getRootViewId() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initUI() {
        List<User> list = ManagerFactory.getInstance().getStudentManager().queryAll();
        if (list.size() > 0) {
            user = list.get(0);
            Log.i("tag", "==========list" + list.get(0).toString());
            //设置图片
            if (!TextUtils.isEmpty(user.getPic())) {
                String url = user.getPic();
                Glide.with(getContext()).load(url).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(ivAvatar);
            }else{
//                Glide.with(getContext()).load(R.drawable.mrtx).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(ivAvatar);
                ivAvatar.setBackgroundResource(R.drawable.mrtx);
            }
            tvcode.setText("ID:"+user.getNickname());
            String isvip = user.getIsvip();
            if(isvip.equals("Y")){
                tvVipTime.setText("vip到期时间"+user.getVipTimeNote());
            }else{
                tvVipTime.setText("您当前还不是vip，请充值");
            }
            //设置名字
            String username = SPUtils.getString(getActivity(),"username","");
            if(username.equals("")){
                resetName();
            }else{
                tvMineName.setText(username);
            }
        }
        srl.setColorSchemeColors(getResources().getColor(R.color.progress_color));

        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateRefreshStatus();
            }
        });
    }



    /**
     * 重新构造本地name
     */
    private void resetName() {
        String a[] = {"忧郁的","高兴的","快乐的","奔跑的","郁闷的","行走的"};
        String b[] = {"黄瓜","篮球","衣服","手机"};
        int namehead=(int)(Math.random()*5);
        int nameend = (int)(Math.random()*4);
        String name = a[namehead]+b[nameend];
        SPUtils.putString(getActivity(),"username",name);
        tvMineName.setText(name);
    }

    public void updateRefreshStatus() {
//        Observable.create(new Observable.OnSubscribe<String>(){
//
//            @Override
//            public void call(Subscriber<? super String> subscriber) {
//                SystemClock.sleep(1000);
//                subscriber.onNext("refresh");
//            }
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<String>() {
//                    @Override
//                    public void call(String s) {
//                        srl.setRefreshing(false);
//                    }
//                });
    }

    @Override
    public void initData() {
        String  picpath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/king/user.jpg";
        File f=new File(picpath);
        if(f.exists()){
            RequestOptions requestOptions1 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.DATA);
            Glide.with(this).load(picpath).apply(requestOptions1).into(ivAvatar);
        }
    }

    @OnClick({R.id.ivLeft, R.id.ivRight, R.id.ivAvatar, R.id.btnLogin, R.id.tvFollow, R.id.tvFans, R.id.tvRecharge, R.id.tvStarLight, R.id.tvContribution, R.id.tvWatch, R.id.tvLevel, R.id.tvTask, R.id.tvGame, R.id.tvSetting, R.id.fab})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivLeft:
                startLogin();
                break;
            case R.id.ivRight:
                startLogin();
                break;
            case R.id.ivAvatar:
//                startLogin();
                AndPermission.with(this)
                        .runtime()
                        .permission(Permission.Group.STORAGE)
                       .onGranted(new Action<List<String>>() {
                           @Override
                           public void onAction(List<String> data) {
                               Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                               intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                               startActivityForResult(intentToPickPic, 1111);
                           }
                       })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {

                            }
                        }).start();

                break;
            case R.id.btnLogin:
                startLogin();
                break;
            case R.id.tvFollow:
                startLogin();
                break;
            case R.id.tvFans:
                startLogin();
                break;
            case R.id.tvRecharge:
                startLogin();
                break;
            case R.id.tvStarLight:
                ToastUtils.showToast(getActivity(),"正在获取价格...");
                getPrice();
                break;
            case R.id.tvContribution:
                getContact();
                break;
            case R.id.tvWatch:
                getShare();
                break;
            case R.id.tvLevel:
                final Dialog dialog =  new Dialog(getActivity(), R.style.myDialog);
                dialog.setContentView(R.layout.dialog_bindperson);
                final EditText etid = dialog.findViewById(R.id.et_bind_id);
                Button btnbind = dialog.findViewById(R.id.btn_bindperson);
                btnbind.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String id = etid.getText().toString();
                        if(TextUtils.isEmpty(id)){
                            ToastUtils.showToast(getActivity(),"邀请码不能为空");
                            return;
                        }
                        bindperson(id);
                        dialog.dismiss();
                    }
                });
                dialog.show();

                break;
            case R.id.tvTask:
                break;
            case R.id.tvGame:
                break;
            case R.id.tvSetting:
                getNotice();
                break;
            case R.id.fab:
                startAbout();
                break;
        }
    }

    /**
     * 绑定用户
     */
    private void bindperson(String id) {
        String userid = App.getUser().getUsercode();
        HttpLoader.getInstance().getBind(userid,id).subscribe(new Observer<BaseCallModel<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseCallModel<String> value) {
                Log.i("tag","===========value"+value);
                ToastUtils.showToast(getActivity(),value.getErrorDesc());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取联系人的方式
     */
    private void getContact() {
        HttpLoader.getInstance().getService().subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                Log.i("tag", "=============abcd" + value);
                Gson gson = new Gson();
                String result = gson.toJson(value);
                BaseCallModel baseCallModel = gson.fromJson(result,BaseCallModel.class);
                Log.i("tag", "=============abcd" + baseCallModel.getData().toString());
                try {
                    if(baseCallModel.getData()!=null){
                        String json1 = gson.toJson(baseCallModel.getData());
                        Log.i("tag", "=============abcd" + json1);
                        List<contactus> us = gson.fromJson(json1,new TypeToken<List<contactus>>(){}.getType());
                        if(us.size()>0){
                            Dialog dialog =  new Dialog(getActivity(), R.style.myDialog);
                            dialog.setContentView(R.layout.dialog_contactus);
                            TextView tvqq = dialog.findViewById(R.id.tvtoqq);
                            TextView tvwx = dialog.findViewById(R.id.tvtowx);
                            tvqq.setText("    "+us.get(0).getContent());
                            tvwx.setText("    "+us.get(1).getContent());
                            dialog.show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.i("tag", "=============abcd" + e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getNotice() {
        HttpLoader.getInstance().getNoticeInfo().subscribe(new Observer<BaseCallModel<Object>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseCallModel<Object> value) {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                try {
                    BaseCallModel baseCallModel = gson.fromJson(json, BaseCallModel.class);
                    if (baseCallModel != null) {
                        String json1 = gson.toJson(baseCallModel.getData());
                        NoticeInfo noticeInfo = gson.fromJson(json1, NoticeInfo.class);
                        if (noticeInfo.getContent() != null) {
//                            ToastUtils.showToast(getActivity(), noticeInfo.getContent() + "");
                            final Dialog dialog =  new Dialog(getActivity(), R.style.myDialog);
                            dialog.setContentView(R.layout.dialog_gonggao);
                            TextView tvqq = dialog.findViewById(R.id.tvggcontent);
                            tvqq.setText(noticeInfo.getContent() + "");
                            dialog.findViewById(R.id.btnggclose).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                        } else {
                            ToastUtils.showToast(getActivity(), "暂时没有公告");
                        }
                    }
                } finally {

                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast(getActivity(), "网络连接不好，请稍后重试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取分享
     */
    private void getShare() {
        HttpLoader.getInstance().getShareInfo().subscribe(new Observer<BaseCallModel<Object>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseCallModel<Object> value) {
                Gson gson = new Gson();
                String json = gson.toJson(value);
                BaseCallModel baseCallModel = gson.fromJson(json, BaseCallModel.class);
                if (baseCallModel != null) {
                    String json1 = gson.toJson(baseCallModel.getData());
                    ShareInfo shareInfo = gson.fromJson(json1, ShareInfo.class);
                    if (shareInfo != null) {
                        new Share2.Builder(getActivity())
                                .setContentType(ShareContentType.TEXT)
                                // 设置要分享的文本内容
                                .setTextContent(shareInfo.getContent())
                                .setTitle("分享三位好友下载可减免会员30元")
                                .build()
                                .shareBySystem();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast(getActivity(), "网络连接不好，请稍后重试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("tag","======resquestCode"+requestCode+"   "+resultCode);
        switch (requestCode) {
            case 1111:
                if(data!=null){
                    Uri uri = data.getData();
                    String filePath = FileUtil.getFilePathByUri(getActivity(), uri);
                    if (!TextUtils.isEmpty(filePath)) {
                        RequestOptions requestOptions1 = new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.DATA);
                        //将照片显示在 ivImage上
                        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                        saveImageToGallery(bitmap);
                        Glide.with(this).load(filePath).apply(requestOptions1).into(ivAvatar);
                    }
                }
                break;
        }
    }
    public void saveImageToGallery(Bitmap bmp) {
        //生成路径
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "/king";
        File appDir = new File(root+dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = "user.jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("tag", "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 获取价格信息
     */
    public void getPrice(){
        HttpLoader.getInstance().getPrice().subscribe(new Observer<BaseCallModel<Object>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseCallModel<Object> value) {
                Log.i("tag","==============value"+value);
                Gson gson = new Gson();
                String json = gson.toJson(value);
                BaseCallModel baseCallModel = gson.fromJson(json,BaseCallModel.class);
                String datajson = gson.toJson(baseCallModel.getData());
                Log.i("tag","==============value"+datajson);
                List<Price> list = gson.fromJson(datajson,new TypeToken<List<Price>>(){}.getType());
                if(list.size()>0){
                    final Dialog dialog =  new Dialog(getActivity(), R.style.myDialog);
                    dialog.setContentView(R.layout.dialog_price);
                    TextView tvone = dialog.findViewById(R.id.tvpriceone);
                    TextView tvtwo = dialog.findViewById(R.id.tvpricetwo);
                    TextView tvthree = dialog.findViewById(R.id.tvpricethree);
                    TextView tvfour = dialog.findViewById(R.id.tvpricefour);
                    tvone.setText(list.get(0).getTitle()+":￥"+list.get(0).getPrice());
                    tvtwo.setText(list.get(1).getTitle()+":￥"+ list.get(1).getPrice());
                    tvthree.setText(list.get(2).getTitle()+":￥"+list.get(2).getPrice());
                    tvfour.setText(list.get(3).getTitle()+":￥"+list.get(3).getPrice());
                    dialog.findViewById(R.id.llpriceone).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.findViewById(R.id.llpricetwo).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.findViewById(R.id.llpricethree).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.findViewById(R.id.llpricefour).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
}
